package team.nine.kuaichezuche.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import team.nine.kuaichezuche.model.VehicleInfo;
import team.nine.kuaichezuche.model.VehicleInstance;
import team.nine.kuaichezuche.repository.VehicleInfoRepository;
import team.nine.kuaichezuche.service.VehicleInfoService;
import team.nine.kuaichezuche.service.VehicleInstanceService;

import java.util.*;

/**
 * 车辆信息服务实现类，实现车辆信息相关的业务逻辑
 */
@Service
public class VehicleInfoServiceImpl implements VehicleInfoService {

    @Autowired
    private VehicleInfoRepository vehicleInfoRepository;
    
    @Autowired
    private VehicleInstanceService vehicleInstanceService;

    /**
     * 创建车辆信息
     */
    @Override
    public VehicleInfo createVehicleInfo(VehicleInfo vehicleInfo) {
        // 这里可以添加验证逻辑，例如检查必填字段
        if (vehicleInfo == null) {
            throw new IllegalArgumentException("车辆信息不能为空");
        }
        if (vehicleInfo.getBrand() == null || vehicleInfo.getBrand().trim().isEmpty()) {
            throw new IllegalArgumentException("品牌不能为空");
        }
        if (vehicleInfo.getModel() == null || vehicleInfo.getModel().trim().isEmpty()) {
            throw new IllegalArgumentException("车型不能为空");
        }

        // 保存车辆信息到数据库
        return vehicleInfoRepository.save(vehicleInfo);
    }

    /**
     * 根据ID获取车辆信息
     */
    @Override
    public VehicleInfo getVehicleInfoById(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("车辆信息ID不能为空");
        }
        return vehicleInfoRepository.findById(id).orElse(null);
    }

    /**
     * 根据品牌获取车辆信息列表
     */
    @Override
    public List<VehicleInfo> getVehicleInfoByBrand(String brand) {
        if (brand == null || brand.trim().isEmpty()) {
            throw new IllegalArgumentException("品牌不能为空");
        }
        return vehicleInfoRepository.findByBrand(brand);
    }

    /**
     * 根据车型获取车辆信息列表
     */
    @Override
    public List<VehicleInfo> getVehicleInfoByModel(String model) {
        if (model == null || model.trim().isEmpty()) {
            throw new IllegalArgumentException("车型不能为空");
        }
        return vehicleInfoRepository.findByModel(model);
    }

    /**
     * 根据动力类型获取车辆信息列表
     */
    @Override
    public List<VehicleInfo> getVehicleInfoByPowerType(VehicleInfo.PowerType powerType) {
        if (powerType == null) {
            throw new IllegalArgumentException("动力类型不能为空");
        }
        return vehicleInfoRepository.findByPowerType(powerType);
    }

    /**
     * 根据品牌和车型获取车辆信息列表
     */
    @Override
    public List<VehicleInfo> getVehicleInfoByBrandAndModel(String brand, String model) {
        if (brand == null || brand.trim().isEmpty()) {
            throw new IllegalArgumentException("品牌不能为空");
        }
        if (model == null || model.trim().isEmpty()) {
            throw new IllegalArgumentException("车型不能为空");
        }
        return vehicleInfoRepository.findByBrandAndModel(brand, model);
    }

    /**
     * 更新车辆信息
     */
    @Override
    public VehicleInfo updateVehicleInfo(VehicleInfo vehicleInfo) {
        if (vehicleInfo == null) {
            throw new IllegalArgumentException("车辆信息不能为空");
        }
        if (vehicleInfo.getId() == null) {
            throw new IllegalArgumentException("车辆信息ID不能为空");
        }

        // 检查车辆信息是否存在
        VehicleInfo existingVehicleInfo = vehicleInfoRepository.findById(vehicleInfo.getId()).orElse(null);
        if (existingVehicleInfo == null) {
            throw new IllegalArgumentException("车辆信息不存在，ID: " + vehicleInfo.getId());
        }

        // 合并非空字段，避免覆盖为null
        if (vehicleInfo.getBrand() != null) {
            existingVehicleInfo.setBrand(vehicleInfo.getBrand());
        }
        if (vehicleInfo.getModel() != null) {
            existingVehicleInfo.setModel(vehicleInfo.getModel());
        }
        if (vehicleInfo.getColor() != null) {
            existingVehicleInfo.setColor(vehicleInfo.getColor());
        }
        if (vehicleInfo.getSeatCount() != null) {
            existingVehicleInfo.setSeatCount(vehicleInfo.getSeatCount());
        }
        if (vehicleInfo.getPowerType() != null) {
            existingVehicleInfo.setPowerType(vehicleInfo.getPowerType());
        }

        // 保存合并后的车辆信息
        return vehicleInfoRepository.save(existingVehicleInfo);
    }

    /**
     * 删除车辆信息
     */
    @Override
    public void deleteVehicleInfo(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("车辆信息ID不能为空");
        }

        // 检查车辆信息是否存在
        VehicleInfo existingVehicleInfo = vehicleInfoRepository.findById(id).orElse(null);
        if (existingVehicleInfo == null) {
            throw new IllegalArgumentException("车辆信息不存在，ID: " + id);
        }

        // 删除车辆信息
        vehicleInfoRepository.deleteById(id);
    }

    /**
     * 获取车辆信息列表（分页）
     * 返回包含车辆信息和车辆实例日租信息的数据
     */
    @Override
    public List<Map<String, Object>> getVehicleInfoList(Integer page, Integer pageSize) {
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        } else if (pageSize > 10) {
            pageSize = 10; // 限制最多返回10辆车
        }

        // 创建分页参数
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        
        // 调用repository获取分页结果
        Page<VehicleInfo> vehiclePage = vehicleInfoRepository.findAll(pageable);
        
        // 获取车辆信息列表
        List<VehicleInfo> vehicleInfoList = vehiclePage.getContent();
        
        // 创建一个新的列表来存储包含车辆信息和日租信息的Map
        List<Map<String, Object>> resultList = new ArrayList<>();
        
        // 对于每辆车辆信息，获取其关联的车辆实例信息
        for (VehicleInfo vehicleInfo : vehicleInfoList) {
            // 创建Map存储车辆信息和日租信息
            Map<String, Object> vehicleData = new HashMap<>();
            
            // 添加车辆基本信息
            vehicleData.put("id", vehicleInfo.getId());
            vehicleData.put("brand", vehicleInfo.getBrand());
            vehicleData.put("model", vehicleInfo.getModel());
            vehicleData.put("color", vehicleInfo.getColor());
            vehicleData.put("seatCount", vehicleInfo.getSeatCount());
            vehicleData.put("powerType", vehicleInfo.getPowerType());
            
            // 获取该车辆信息对应的所有车辆实例
            List<VehicleInstance> vehicleInstances = vehicleInstanceService.getVehicleInstancesByVehicleInfoId(vehicleInfo.getId());
            
            // 存储日租信息（如果有车辆实例）
            if (vehicleInstances != null && !vehicleInstances.isEmpty()) {
                // 取第一个车辆实例的日租作为参考
                VehicleInstance firstInstance = vehicleInstances.get(0);
                vehicleData.put("dailyRate", firstInstance.getDailyRate());
                
                // 也可以存储所有车辆实例的信息
                List<Map<String, Object>> instanceDetails = new ArrayList<>();
                for (VehicleInstance instance : vehicleInstances) {
                    Map<String, Object> instanceMap = new HashMap<>();
                    instanceMap.put("instanceId", instance.getId());
                    instanceMap.put("licensePlate", instance.getLicensePlate());
                    instanceMap.put("dailyRate", instance.getDailyRate());
                    instanceMap.put("mileage", instance.getMileage());
                    instanceMap.put("availableStart", instance.getAvailableStart());
                    instanceMap.put("availableEnd", instance.getAvailableEnd());
                    instanceMap.put("status", instance.getStatus());
                    instanceMap.put("rentalCount", instance.getRentalCount());
                    instanceDetails.add(instanceMap);
                }
                vehicleData.put("instances", instanceDetails);
            } else {
                // 如果没有车辆实例，日租信息设为null
                vehicleData.put("dailyRate", null);
                vehicleData.put("instances", new ArrayList<>());
            }
            
            // 添加到结果列表
            resultList.add(vehicleData);
        }
        
        // 返回包含车辆信息和日租信息的列表
        return resultList;
    }

    /**
     * 获取车辆信息总数
     */
    @Override
    public int getVehicleInfoCount() {
        // 调用repository获取车辆总数
        return (int) vehicleInfoRepository.count();
    }
}